package org.hitchhike.utils;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileUtil {

  @Value("${org.hitchhike.file.path}")
  private String path;

  /**
   * @return the path
   */
  public String getPath() {
    return path;
  }

  public String getRealPath(HttpServletRequest request) {
    String realPath = request.getServletContext().getRealPath(path);

    File file = new File(realPath);
    if (!file.exists() && !file.isDirectory()) {
      file.mkdirs();
    }
    return realPath;
  }

  public void upload(HttpServletRequest request, MultipartFile file, String fileName)
      throws IllegalStateException, IOException {
    if (!file.isEmpty()) {
      String realPath = getRealPath(request);
      file.transferTo(new File(realPath + fileName));
    }
  }

  public String getPrefix(String originalFilename) {
    String prefix = null;
    if (!originalFilename.isEmpty()) {
      prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
    }
    return prefix;
  }

}
